import axios from 'axios'
import { ElMessage } from 'element-plus'

let progress = null
const requestMap = new Map()

export function setProgressInstance(instance) {
  progress = instance
}

function generateRequestId() {
  return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 请求管理类
class RequestManager {
  static addRequest(requestId, config) {
    requestMap.set(requestId, {
      id: requestId,
      url: config.url,
      method: config.method,
      startTime: Date.now()
    })

    // 第一个请求时开始进度条
    if (requestMap.size === 1) {
      progress?.start()
    }
  }

  static removeRequest(requestId) {
    const request = requestMap.get(requestId)
    if (request) {
      requestMap.delete(requestId)
    }

    // 所有请求完成时结束进度条
    if (requestMap.size === 0) {
      progress?.finish()
    }
  }

  static getStatus() {
    return {
      count: requestMap.size,
      requests: Array.from(requestMap.values())
    }
  }

  static clear() {
    requestMap.clear()
    progress?.finish()
    console.log('🧹 手动清理请求栈')
  }
}

const interceptor = () => {
  http.interceptors.request.use(
    async config => {
      const requestId = generateRequestId()
      config.requestId = requestId

      // 添加请求到管理器
      RequestManager.addRequest(requestId, config)

      // 在请求发送之前做些什么
      if (config.url.includes('/api/user/login')) {
        // 如果是登录请求，不添加token
        return config
      }
      const token = localStorage.getItem('token')
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
      return config
    },
    async error => {
      if (error.config?.requestId) {
        RequestManager.removeRequest(error.config.requestId)
      }
      console.error('请求错误:', error)
      return Promise.reject(error)
    }
  )
  http.interceptors.response.use(
    async response => {
      // 对响应数据做点什么
      if (response.config?.requestId) {
        RequestManager.removeRequest(response.config.requestId)
      }
      return response
    },
    async error => {
      if (error.config?.requestId) {
        RequestManager.removeRequest(error.config.requestId)
      }

      let customMsg = ''
      if (error.response) {
        // 服务器响应了，但状态码不是2xx
        switch (error.response.status) {
          case 404:
            customMsg = '请求的接口不存在，请检查API地址'
            break
          case 401:
            location.href = '/login'
            ElMessage.error('未授权，请登录')
            break
          case 403:
            customMsg = '禁止访问，请联系管理员'
            break
          case 500:
            break
          default:
            break
        }
      }

      const data = error.response?.data || {}
      const message = data.message || customMsg || '哎呀网络连接不畅，请刷新重试～'
      if (message) {
        ElMessage.error(message)
      }

      // 返回一个默认的响应对象，避免程序崩溃
      return Promise.resolve({
        data: error.response?.data || {},
        status: error.response?.status || 0,
        error: true,
        message: error.message
      })
    }
  )
}
const http = axios.create()
interceptor()

const api = {
  login(data) {
    return http.post('/api/user/login', data)
  },
  logout() {
    return http.post('/api/user/logout')
  },
  getUserInfo() {
    return http.post('/api/user/info')
  },
  projectGroupList(data) {
    return http.post('/api/projectGroup/pageList', data)
  },
  projectGroupSave(data) {
    return http.post('/api/projectGroup/save', data)
  },
  projectGroupDelete(data) {
    return http.post('/api/projectGroup/delete', data)
  },
  projectGroupBatchDelete(data) {
    return http.post('/api/projectGroup/batchDelete', data)
  },
  projectGroupInfo(id) {
    return http.post('/api/projectGroup/info', { id: id })
  }
}

export default api
